#include "StdAfx.h"
#include "GroupMgr.h"
#include <algorithm>

#include "dao/groupdao.h"
#include "dao/DAOFactory.h"

CGroupMgr::CGroupMgr(void)
{
	m_pGroupDao =  CDAOFactory::GetGroupDao();
}

CGroupMgr::~CGroupMgr(void)
{
	if(m_pGroupDao)
		delete m_pGroupDao;
}



void  CGroupMgr::LoadGroupInfo()
{

	CGroup *     pGroup;
	if(m_bLoad)
		return;

	do 
	{
		if(!m_pGroupDao->GetAllGroup())
			break;
		pGroup = new CGroup;
		while(m_pGroupDao->EnumGroup(*pGroup))
		{
			m_groupVector.push_back(pGroup);
			pGroup = new CGroup;
		}

		if(pGroup)
			delete pGroup;
	} while (FALSE);

	m_bLoad = true;
	return ;

}

CGroup*  CGroupMgr:: FindGroupById(int id)
{
	if(id < 0)
		return NULL;
	FindGroup  findGroup;
	findGroup.id =id;

	vector<CGroup*>::iterator  it = std::find_if(m_groupVector.begin(),m_groupVector.end(),findGroup);
	if(it == m_groupVector.end())
		return NULL;
	return (*it);

}


bool  CGroupMgr::IsGroupExist(CString&  groupName)
{
	if(groupName == "")
		return false;

	GroupFinder  groupFinder;
	groupFinder.name =groupName;

	vector<CGroup*>::iterator  it = std::find_if(m_groupVector.begin(),m_groupVector.end(),groupFinder);
	if(it == m_groupVector.end())
		return false;
	return true;
}

bool CGroupMgr::AddAGroup(CGroup* pGroup)
{
	bool bOk;
	if(pGroup == NULL)
		return false;
	do 
	{
		if((!m_pGroupDao->AddAGroup(*pGroup)) || (!m_pGroupDao->GetGroupIdByName(*pGroup)))
		{
			delete pGroup;
			bOk= false;
			break;
		}
		m_groupVector.push_back(pGroup);
		bOk = true;

	} while (false);


	return bOk;


}


bool CGroupMgr::DelAGroup(CGroup* pGroup)
{
	if(pGroup == NULL)
		return false;

	bool bOk= false;

	vector<CGroup*>::iterator  it;
	do 
	{
		if(!m_pGroupDao->DelAGroup(pGroup->m_groupID))
		{
			break;
		}
		for(it = m_groupVector.begin();it != m_groupVector.end();it++)
		{
			if((*it )== pGroup )
			{
				m_groupVector.erase(it);
				break;
			}
		}
		delete pGroup;
		bOk = true;

	} while (FALSE);

	return bOk;

}


void  CGroupMgr::Clear()
{


	CGroup*  pGroup = NULL;
	while(m_groupVector.size())
	{
		pGroup = m_groupVector.back();
		m_groupVector.pop_back();
		if(pGroup)
			delete  pGroup;
	}
	m_bLoad = false;



}

void  CGroupMgr::GenerateKey(CString&  strKey)
{
	int i ;
	TCHAR  lpStr[65] = {0};
	for(i=0 ; i < 64 ;i++)
	{
		lpStr[i] =65+rand()%26;
	}
	strKey = lpStr;
}
